<!DOCTYPE html>
<html class="x-admin-sm">

<head>
  <meta charset="UTF-8">
  <title></title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
    content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
  <link rel="stylesheet" href="./css/font.css">
  <link rel="stylesheet" href="./css/xadmin.css">
  <link rel="stylesheet" href="./css/link_list.css">
  <link rel="stylesheet" href="./css/link.css">
  <script src="./lib/layui/layui.all.js" charset="utf-8"></script>
  <script type="text/javascript" src="./js/xadmin.js"></script>
  <!--[if lt IE 9]>
          <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
          <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->

  <style>
    #nav {
      display: flex;
      justify-content: space-between;
    }

    #nav ul {
      display: flex;
      width: 140px;
      justify-content: space-between;
      /* background-color: pink; */
    }

    #nav ul li a {
      display: block;
      height: 100%;
    }

    #btnAddCate,
    #tex {
      background-color: #ecf5ff;
      color: #40b5ff;
      border: 1px solid #40b5ff;
    }

    #btnAddCate:hover {
      background-color: #409eff;
      color: #ffffff;

    }

    .active {
      border-bottom: 2px solid #409eff;
    }
  </style>
</head>

<body>
  <div class="x-nav">
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">演示</a>
      <a>
        <cite>导航元素</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
      onclick="location.reload()" title="刷新">
      <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
  </div>
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <!-- 这是友情链接列表、修改、删除、增加 -->

      <div class="layui-card">
        <div class="layui-card-header" id="nav">
          <ul id="myul">
            <li class="layui-this" data-id="1"><a href="#">文字链接</a></li>
            <li data-id="2"><a href="#">图片链接</a></li>
          </ul>
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="btnAddCate">+
            新增</button>
        </div>
        <div class="layui-card-body">

          <!-- 备用： 添加弹出层的表单内容结构 -->
          <form style="display: none;" id="addForm" class="layui-form">
            <!-- 第一行 分类名称 -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类名称</label>
              <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
            <!-- 第二行 分类别名  -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类别名</label>
              <div class="layui-input-block">
                <input type="text" name="alias" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
            <!-- 第三行 按钮 -->
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">确认添加</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
              </div>
            </div>
          </form>

          <!-- 备用： 编辑弹出层的表单内容结构 -->
          <form style="display: none;" id="editForm" class="layui-form">
            <!-- 第一行 分类名称 -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类名称</label>
              <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
            <!-- 第二行 分类别名  -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类别名</label>
              <div class="layui-input-block">
                <input type="text" name="alias" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
            <!-- 第三行 按钮 -->
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">确认修改</button>
              </div>
            </div>
          </form>

          <!-- 表格区域 -->
          <table class="layui-table">
            <colgroup>
              <col width="0">
              <col width="0">
              <col width="200">
              <col>
            </colgroup>
            <thead>
              <tr>
                <th style="font-weight: 700;">#</th>
                <th style="font-weight: 700;" class="title">标题</th>
                <th style="font-weight: 700;" class="des">链接描述</th>
                <th style="font-weight: 700;">链接类型</th>
                <th style="font-weight: 700;">链接地址</th>
                <th style="font-weight: 700;">操作</th>
              </tr>
            </thead>
            <tbody id="tbody">
              <tr>
                <td>1</td>
                <td>keji</td>
                <td>keji</td>
                <td>文字类型</td>
                <td>地址</td>
                <td>
                  <button type="button" class="layui-btn layui-btn-sm"
                    style="background-color: #409eff; border-radius: 45%;">
                    <i class="layui-icon">&#xe642;</i>
                  </button>
                  <button type="button" class="layui-btn layui-btn-sm"
                    style="background-color: #f56c6c;border-radius: 45%;">
                    <i class="layui-icon">&#xe640;</i>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页区域 -->
        <div id="page-box"></div>
      </div>
    </div>
</body>
<script src="./js/jquery.min.js"></script>
<script src="./js/axios.min.js"></script>
<script src="./js/ajaxBase.js"></script>
<script>


  query = {
    page: 1,
    limit: 10,
    type: 1
  }
  // 拿到列表数据,渲染页面
  async function getList() {
    const listData = await axios.get('/ydd_link/list', { params: query })

    // console.log(listData);
    $('#tbody').html(listData.data.data.data.map((item, index) => {
      return `
            <tr>
                <td>${index + 1}</td>
                <td>${query.type === 1 ? item.title : item.des}</td>
                <td>${query.type === 1 ? item.des : `<img src="http://124.223.14.236:8060/${item.img}" alt="">`}</td>
                <td><button type="button" class="layui-btn ${query.type === 1 ? 'textbtn' : 'imgbtn'}" id="tex">${item.type = item.type === '1' ? '文字类型' : '图片类型'}</button></td>
                <td>${item.url}</td>
                <td>
                  <button type="button" id="editBtn" data-id='${item.id}' class="layui-btn layui-btn-sm"
                    style="background-color: #409eff; border-radius: 35%;">
                    <i class="layui-icon">&#xe642;</i>
                  </button>
                  <button id="delBtn" data-id='${item.id}' type="button" class="layui-btn layui-btn-sm"
                    style="background-color: #f56c6c;border-radius: 35%;">
                    <i class="layui-icon">&#xe640;</i>
                  </button>
                </td>
              </tr>
      `
    }).join(''))

    getPage(listData)
  }

  getList()


  let q = false
  let p = false

  $('#myul').on('click', 'li', function () {
    const id = $(this).data('id')
    $('.title').html(id === 1 ? '标题' : '链接描述')
    $('.des').html(id === 1 ? '链接描述' : '链接图片')
    query.type = id
    getList()
    if (id === 1) {
      q = true
      p = false
    } else {
      p = true
      q = false
    }
  })

  const layer = layui.layer
  const form = layui.form

  // 新增 弹出层显示框的内容

  let addFormStr = `
              <form id="addForm" class="layui-form">

                          <div class="layui-form-item">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接类型</label>
                          <div class="layui-input-block">
                            <select name="type" lay-filter="aihao" style="height:80px;">
                              <option>请选择</option>
                              <option value="0">图片类型</option>
                              <option value="1">文字类型</option>
                            </select>
                          </div>
                        </div>

                        <div class="layui-form-item layui-hide"  id='tittle'>
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*标题</label>
                          <div class="layui-input-block">
                            <input type="text" name="title" placeholder="请输入链接标题名称" autocomplete="off" class="layui-input">
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接地址</label>
                          <div class="layui-input-block">
                            <input type="text" name="url" placeholder="请输入链接地址名称" autocomplete="off" class="layui-input">
                          </div>
                        </div>
                        
                        <div class="layui-form-item layui-form-text">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接描述</label>
                          <div class="layui-input-block">
                            <textarea name="des" placeholder="请输入链接地址描述" class="layui-textarea"></textarea>
                          </div>
                        </div>

                        <div class="layui-form-item layui-form-text layui-hide" id='pic'>
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接图片</label>
                          <div class="layui-input-block" >

                            <button type="button" class="layui-btn"  id="btnChooseImage" style="background-color: #409eff;">选择图片</button>
                            <input type="file" name='img' id="file" style="display:none;line-height:36px" accept="image/jpeg,image/png,image/bmp,image/gif" />

                            
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="formDemo" >确认添加</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="NOBTN">取消</button>
                          </div>
                        </div>


              </form>`

  let indexAddForm
  // <button class="layui-btn"  id="btnChooseImage" style="background-color: #409eff;">选择图片</button>
  // <div id='addpic' style="width:400px;height:80px;background-color:pink;">
  //     <img src="" alt="">
  //   </div>
  // ==================================添加功能===================================

  // 给添加按钮注册点击事件，调用layer的open方法，显示添加的模态框
  $('#btnAddCate').click(function () {
    indexAddForm = layer.open({
      type: 1,
      area: ['600px', '500px'],
      title: ['添加友情链接', 'font-size:20px'],
      content: addFormStr,//添加显示框内容
    });

    form.render()
    form.on('select', function (data) {
      // console.log(data.value); //得到被选中的值
      if (data.value === '1') {
        $('#tittle').removeClass('layui-hide')
        $('#pic').addClass('layui-hide')

      } else {
        $('#pic').removeClass('layui-hide')
        $('#tittle').addClass('layui-hide')
      }
    });

    let fileList
    $('#btnChooseImage').on('click', function () {
      $('#file').click()
    })

    $('body').on('change', '#file', function (e) {
      fileList = e.target.files
      const imgUrl = URL.createObjectURL(fileList[0])
      console.log(imgUrl);
      getImg(imgUrl)
    })
  })




  // 事件委托，给确认添加按钮注册表单提交事件
  getImg()
  function getImg(imgUrl) {
    $('body').on('submit', '#addForm', async function (e) {
      e.preventDefault();
      // 收集addForm表单的数据
      const dataForm = $(this).serialize()
      // console.log(dataForm);

      let data = {}
      $(this).serialize().split('&').map(item => item.split('=')).forEach(([one, two]) => data[one] = decodeURI(two))
      // console.log(data);
      if (imgUrl) {
        data['img'] = imgUrl
      }
      else {
        data['img'] = ''
      }
      // console.log(data);

      // const newdata = JSON.stringify(data)
      // console.log(newdata);
      const res = await axios.post('/ydd_link/add', data)
      // console.log(res);

      layer.msg('添加成功')
      layer.close(indexAddForm)

      getList()

    })
  }
  $('body').on('click', '#NOBTN', function () {
    layer.close(indexAddForm)
  })

  // ========================================删除功能=====================================
  $('body').on('click', '#delBtn', async function () {
    const Id = $(this).attr('data-id')
    // console.log(Id);
    layer.confirm('确认删除吗?', { icon: 3, title: '提示' }, function (index) {
      //   //do something
      axios.get(`/ydd_link/del?id=${Id}`).then(res => {
        // 删除失败
        // console.log(res);
        if (res.data.errno !== 0) {
          return layer.msg('删除失败')
        }

        // 解决删除的bug，去加载上一页的数据
        // 当这一页的删除按钮剩一个的时候，表示这一条数据删除后，这一页数据为空了，此时页码要减一
        // 页码最小值是1 
        // if ($('#delBtn').length === 1) {
        //   if (query.page === 1) {
        //     query.page = 1
        //   } else {
        //     query.page = query.page - 1
        //   }
        // }
        layer.msg('删除成功')
        // 关闭弹窗
        layer.close(index);
        // 重新渲染
        getList()
      })
    });
  })


  // ========================================编辑功能=====================================
  let indexEditForm
  let editFormStr = `
              <form id="editForm" class="layui-form" lay-filter="formEdit">

                          <div class="layui-form-item">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接类型</label>
                          <div class="layui-input-block">
                            <select name="type" lay-filter="aihao" style="height:80px;">
                              <option>请选择</option>
                              <option value="0">图片类型</option>
                              <option value="1">文字类型</option>
                            </select>
                          </div>
                        </div>

                        <div class="layui-form-item layui-hide"  id='tittle'>
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*标题</label>
                          <div class="layui-input-block">
                            <input type="text" name="title" placeholder="请输入链接标题名称" autocomplete="off" class="layui-input">
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接地址</label>
                          <div class="layui-input-block">
                            <input type="text" name="url" placeholder="请输入链接地址名称" autocomplete="off" class="layui-input">
                          </div>
                        </div>
                        
                        <div class="layui-form-item layui-form-text">
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接描述</label>
                          <div class="layui-input-block">
                            <textarea name="des" placeholder="请输入链接地址描述" class="layui-textarea"></textarea>
                          </div>
                        </div>

                        <div class="layui-form-item layui-form-text layui-hide" id='pic'>
                          <label class="layui-form-label" style="font-size:14px;font-weight:700;vertical-align:auto;">*链接图片</label>
                          <div class="layui-input-block" >

                            <button type="button" class="layui-btn"  id="btnChooseImage" style="background-color: #409eff;">选择图片</button>
                            <input type="file" name='img' id="file" style="display:none;line-height:36px" accept="image/jpeg,image/png,image/bmp,image/gif" />

                            
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="formDemo" id='yesBtn'>确认修改</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="noBtn">取消</button>
                          </div>
                        </div>

              </form>`


  let id
  $('body').on('click', '#editBtn', async function () {

    indexEditForm = layer.open({
      type: 1,
      area: ['600px', '500px'],
      title: ['修改友情链接', 'font-size:20px'],
      content: editFormStr,//添加显示框内容
    });

    form.render()

    id = $(this).attr('data-id')
    // console.log(id);
    const res = await axios.get('/ydd_link/rowInfo', { params: { id: id } })
    // console.log(res);

    form.val('formEdit', res.data.data)

    form.on('select', function (data) {
      // console.log(data.value); //得到被选中的值
      if (data.value === '1') {
        $('#tittle').removeClass('layui-hide')
        $('#pic').addClass('layui-hide')

      } else {
        $('#pic').removeClass('layui-hide')
        $('#tittle').addClass('layui-hide')
      }
    });
  })



  $('body').on('submit', '#editForm', async function (e) {
    e.preventDefault()
    let data = {}
    $(this).serialize().split('&').map(item => item.split('=')).forEach(([one, two]) => data[one] = decodeURI(two))
    data['img'] = ''
    data['type'] = '1'
    data['id'] = +id
    console.log(data);
    const res = await axios.post('/ydd_link/update', data)
    console.log(res);
    layer.msg('修改成功')
    layer.close(indexEditForm)

    getList()

  })

  $('body').on('click', '#noBtn', function () {
    layer.close(indexEditForm)
  })





  const laypage = layui.laypage
  // 函数封装页码
  function getPage(listData) {
    laypage.render({
      elem: 'page-box', //注意，这里的 test1 是 ID，不用加 # 号
      count: listData.data.data.count,  //数据总数，从服务端得到
      limit: query.limit,//每页显示的条数
      curr: query.page, //起始页
      layout: ["count", "limit", "prev", "page", "next", "skip"],
      limits: [1, 2, 3, 5, 8, 10],

      jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        // 点击分页，加载出对应分页的数据
        query.page = obj.curr   //修改当前页的页码
        query.limit = obj.limit  //修改每页显示的条数

        //首次不执行
        if (!first) {
          //do something
          getList()
        }
      }
    });
  }


</script>

</html>